import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import java.io.File;
import java.io.FileOutputStream;
import java.util.*;

public class SendBatchMail {
    private static final Log log = LogFactory.getLog(SendBatchMail.class);

    public static String goSendMail(Map<String, Object> receviceMap) {

        String rec_guid = null;
        String sendAdderss = null;
        String receviceAddress = null;
        String ccUser = null;
        String bccUser = null;
        String subject = null;
        String content = null;
        String emlFilePath = null;
        String contenttype = null;

        List attachmentList = new ArrayList();
        String attachResult = "";


        Properties properties = new Properties();
        // 创建Session对象
        Session session = Session.getInstance(properties);


        try {
            long startTime = System.currentTimeMillis();
            // 创建邮件的实例对象
            MimeMessage message = new MimeMessage(session);

            rec_guid = receviceMap.get("rec_guid").toString();
            sendAdderss = receviceMap.get("fromUser").toString();
            receviceAddress = receviceMap.get("receviceAddress").toString();
            ccUser = receviceMap.get("ccUser").toString();
            ccUser = receviceMap.get("ccUser").toString();
            bccUser = receviceMap.get("bccUser").toString();
            subject = receviceMap.get("subject").toString();
            content = receviceMap.get("content").toString();
            emlFilePath = receviceMap.get("emlFilePath").toString();
            receviceAddress = receviceMap.get("receviceAddress").toString();
            attachmentList = (List<?>) receviceMap.get("attachmentList");
            contenttype = receviceMap.get("contenttype").toString();

            message.setFrom(new InternetAddress(sendAdderss));

            // 设置多个收件地址
            if (null != receviceAddress && !receviceAddress.isEmpty()) {
                @SuppressWarnings("static-access") InternetAddress[] internetAddressCC = new InternetAddress().parse(receviceAddress);
                message.setRecipients(RecipientType.TO, internetAddressCC);
            }

            // 设置多个抄送地址
            if (null != ccUser && !ccUser.isEmpty()) {
                @SuppressWarnings("static-access") InternetAddress[] internetAddressCC = new InternetAddress().parse(ccUser);
                message.setRecipients(RecipientType.CC, internetAddressCC);
            }

            // 设置多个密送地址
            if (null != bccUser && !bccUser.isEmpty()) {
                @SuppressWarnings("static-access") InternetAddress[] internetAddressBCC = new InternetAddress().parse(bccUser);
                message.setRecipients(RecipientType.BCC, internetAddressBCC);
            }

            message.setSubject(subject, "UTF-8");
            MimeMultipart msgMultipart = new MimeMultipart("mixed");
            MimeBodyPart mbpContent = new MimeBodyPart();

            // 判断处理邮件格式类型
            if ("html".equals(contenttype)) {
                mbpContent.setContent(content, "text/html;charset=utf-8");
            } else {
                mbpContent.setText(content);
            }
            msgMultipart.addBodyPart(mbpContent);

            // 处理邮件附件List
            if (attachmentList != null && attachmentList.size() > 0) {
                for (int j = 0; j < attachmentList.size(); ++j) {
                    MimeBodyPart attachment = new MimeBodyPart();
                    DataHandler dh = new DataHandler(new FileDataSource((String) attachmentList.get(j)));
                    attachment.setDataHandler(dh);
                    attachment.setFileName(MimeUtility.encodeWord(dh.getName()));
                    msgMultipart.addBodyPart(attachment);
                }
            }

            message.setContent(msgMultipart);

            attachResult = writeEml(session, message, emlFilePath, rec_guid);

        } catch (Exception e) {
            log.error("批量发送异常！", e);

        } finally {

            log.debug("成功关闭会话");
        }
        return attachResult;

    }

    public static String writeEml(Session session, MimeMessage message, String emlFilePath, String rec_guid) {

        long tstartTime, tendTime, startTime, endTime;

        tstartTime = System.currentTimeMillis();
        log.debug("Rec_Guid[" + rec_guid + "]-File写入本地文件参数 Start time:" + tstartTime + "-emlFilePath:" + emlFilePath + "-message:" + message);

        // 将文件内容写入本地服务器
        int i = 0;
        File dirAll = new File(emlFilePath);

        do {
            startTime = System.currentTimeMillis();
            FileOutputStream fos = null;
            log.debug("Rec_Guid[" + rec_guid + "]-File[" + i + "]开始将文件内容写入本地服务器:" + "-emlFilePath:" + emlFilePath + "-message:" + message);
            try {
                // 文件夹路径是否存在不存在则创建
                File dir = new File(dirAll.getParent());
                if (!dir.exists()) {
                    log.debug("Rec_Guid[" + rec_guid + "]-File[" + i + "]创建EML所需路径:" + dirAll.getParent());
                    dir.mkdirs();
                }

                // 检查目标文件是否存在，不存在则创建
                if (!dirAll.exists()) {
                    log.debug("Rec_Guid[" + rec_guid + "]-File[" + i + "]创建写入EML文件:" + dirAll.getName());
                    dirAll.createNewFile();
                }
                // 向目标文件中写入内容
                fos = new FileOutputStream(dirAll);
                try {
                    message.writeTo(fos);
                } catch (MessagingException e) {
                    log.error("Rec_Guid[" + rec_guid + "]-File[" + i + "]写入EML文件失败...", e);
                }
                log.debug("Rec_Guid[" + rec_guid + "]-File[" + i + "]写入EML文件完成...");

            } catch (Exception e) {
                log.error("Rec_Guid[" + rec_guid + "]-File[" + i + "]写入EML文件失败：", e);
                e.printStackTrace();
            } finally {
                if (null != fos) {
                    try {
                        fos.close();
                    } catch (Exception e) {
                        log.error("Rec_Guid[" + rec_guid + "]-File[" + i + "]关闭文件流失败：", e);
                    }
                }

                endTime = System.currentTimeMillis();

                log.debug("Rec_Guid[" + rec_guid + "]-File[" + i + "]写入文件结束 Start time:" + startTime + "; End time:" + endTime + "; Run Time:" + (endTime - startTime) + "(ms)");

                i++;

            }
        } while (!dirAll.exists() && i < 3);

        tendTime = System.currentTimeMillis();
        log.debug("Rec_Guid[" + rec_guid + "]-File写入本地文件结束 End time:" + tendTime + "; Run Time:" + (tendTime - tstartTime) + "(ms)");

        return emlFilePath;

    }

}

class RunException extends Exception {
    /**
     * RunException
     */
    private static final long serialVersionUID = 1L;

    public RunException(String msg) {
        super(msg);
    }
}